package com.sinping.qh.utils.word;

import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author jiahuaiqing
 * @create 2018/7/11
 */
public class Base64Util {

//    public static void main(String[] args){
//        String s = GetImageStrFromUrl("http://172.7.0.206/images/qh/image/1/2018-07-06/471994cfe86b4fe783904cbbabbb465d.jpg");
//    }

    /**
     * 将一张网络图片转化成Base64字符串
     * @param imgURL 网络图片地址
     * @return
     */
    public static String GetImageStrFromUrl(String imgURL) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            String result="";
            int i=0;
            while (result!=null) {
                i = is.read(by);
                if(i!=-1) {
                    data.write(by, 0, i);
                }else
                {
                    result=null;
                }
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }


    /**
     * 该方法用来将指定的文件转换成base64编码
     * @param path:本地图片路径(物理路径E:/123.png)
     * **/
    public static String getImageStr(String path){
        //1、校验是否为空
        if(path==null || path.trim().length()<=0){return "";}

        //2、校验文件是否为目录或者是否存在
        File picFile = new File(path);
        if(picFile.isDirectory() || (!picFile.exists())) return "";

        //3、校验是否为图片
        try {
            BufferedImage image = ImageIO.read(picFile);
            if (image == null) {
                return "";
            }
        } catch(IOException ex) {
            ex.printStackTrace();
            return "";
        }

        //4、转换成base64编码
        String imageStr = "";
        try {
            byte[] data = null;
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            imageStr = encoder.encode(data);
        } catch (Exception e) {
            imageStr="";
            e.printStackTrace();
        }

        return imageStr;
    }

}
